<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售时间" prop="createdTime">
        <el-date-picker clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择销售时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售数量" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入销售数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售单价" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入销售单价"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品编号" prop="price">
        <el-input
            v-model="queryParams.drugId"
            placeholder="请输入药品编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品名称" prop="price">
        <el-input
            v-model="queryParams.drugId"
            placeholder="请输入药品名称"
            clearable
            @keyup.enter="(val)=>{queryfilter(val,'drugName')}"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div v-if="showData && check()">
      <el-descriptions  v-if="showData[0]" title="供货商统计">
        <el-descriptions-item label="供货商">{{showData[0]?.provider}}</el-descriptions-item>
        <el-descriptions-item label="售出药品计数">{{cal().cnt}}</el-descriptions-item>
        <el-descriptions-item label="总价">{{cal().sum}}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-table ref="tableRef" v-loading="loading" :data="saleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售ID" align="center" prop="id" />
      <el-table-column label="销售时间" align="center" prop="createdTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售数量" align="center" prop="number" />
      <el-table-column label="药品编号" align="center" prop="drugId" />
      <el-table-column label="药品名称" align="center" prop="drugId" >
        <template #default="scope">
          <span>{{ findDrug(scope.row.drugId)?.drugName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="药品功效" align="center" prop="drugId" >
        <template #default="scope">
          {{findDrug(scope.row.drugId)?.func}}
        </template>
      </el-table-column>
      <el-table-column label="药品所治疾病" align="center" prop="drugId" >
        <template #default="scope">
          {{findDrug(scope.row.drugId)?.disease}}
        </template>
      </el-table-column>
      <el-table-column label="药品类型" align="center" prop="drugId" >
        <template #default="scope">
          {{findDrug(scope.row.drugId)?.drugType}}
        </template>
      </el-table-column>
      <el-table-column label="供货商" align="center" prop="drugId" :filtered-value="filtered_value" :filter-multiple="false" :filters="filter_provider" :filter-method="filter_provider_func" >
        <template #default="scope">
          {{findDrug(scope.row.drugId)?.provider}}
        </template>
      </el-table-column>
      <el-table-column label="销售单价" align="center" prop="price" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="saleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售时间" prop="createdTime">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择销售时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入销售数量" />
        </el-form-item>
        <el-form-item label="销售单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入销售单价" />
        </el-form-item>
        <el-form-item label="药品名称" prop="price">
          <el-select v-model="form.drugId" placeholder="请选择药品名称">
            <el-option
              v-for="item in drugs"
              :key="item.id"
              :label="item.drugName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sale">
import { listSale, getSale, delSale, addSale, updateSale } from "@/api/system/sale";
import {listDrug} from "@/api/system/drug.js";
import {listProvider} from "@/api/system/provider.js";
import {watch} from "vue";

const { proxy } = getCurrentInstance();

const showData = ref([]);
const saleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const drugs = ref([]);
const providers = ref([]);
const filter_provider = ref([]);
const filtered_value = ref([]);
const showDataBool = ref([]);
listDrug().then(response => {
  drugs.value = response.rows;
});
const queryfilter = (val,key)=>{
  saleList.value = saleList.value.map(item=>{
    console.log(item)
    let drug = findDrug(item.drugId)
    item.provider = drug.provider
    item.drugName = drug.drugName
    item.drugType = drug.drugType
    return item
  })
  alert(saleList.value)
  saleList.value = saleList.value.filter(item => {return item[key].includes(val)});
}

const findDrug = (id) => {
  return drugs.value.find(item => item.id === id);
}

const tableRef = ref(null)
const filterProvider = ()=>{
  listProvider().then(response => {
    providers.value = response.rows;
  }).then(()=>{
    filter_provider.value = providers.value.map(item => {return {'text':item.name,'value':item.name}});
  }).then(()=>{
    console.log(filter_provider.value);
  })
}
filterProvider()
const filterVal = ref('')
const check = ()=>{
  return tableRef.value.data.some(item=> {return findDrug(item.drugId).provider === filterVal.value})
}

const filter_provider_func = (val,row)=>{
  // if(flag.value === 1 ){
  //   showData.value = []
  // }
  filterVal.value =val
  if(findDrug(row.drugId).provider === val){
    showData.value = []
    // showData.value = tableRef.value.data.filter(item => {return findDrug(item.drugId).provider === val});
    tableRef.value.data.forEach(item=>{
      let ii = findDrug(item.drugId)
      item.provider = ii.provider
      if (item.provider === val){
        showData.value.push(item)
      }
    })
    return true
  }
  return false
}
const cal = () => {
  let cnt = 0
  let sum = 0
  showData.value.forEach(item=>{
    cnt +=item.number
    sum += (item.price * item.number)
  })
  console.log(cnt,sum)
  return {'cnt':cnt,'sum':sum}
};


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugId: null,
    createdTime: null,
    number: null,
    price: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询销售列表 */
function getList() {
  loading.value = true;
  listSale(queryParams.value).then(response => {
    saleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(e => {
    console.log(e);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createdTime: null,
    number: null,
    price: null
  };
  proxy.resetForm("saleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  try {
    queryParams.value.pageNum = 1;
    getList()
  }
  catch (e) {

  }

}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加销售";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSale(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改销售";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["saleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSale(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSale(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除销售编号为"' + _ids + '"的数据项？').then(function() {
    return delSale(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/sale/export', {
    ...queryParams.value
  }, `sale_${new Date().getTime()}.xlsx`)
}

getList();
</script>
